<template> 
  <div>
    <el-upload
      :class="uploadFileClass"
      :multiple="true"
      :headers="headers"
      :action="localUploadUrl"
      :data="moduleData"
      list-type="picture"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-change="handFileChange"
      :on-success="handleUploadSuccess"
      :on-preview="handlePreview"
      :limit="maxCount"
      :on-exceed="handleExceed">
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB
      <span v-if="prcScaleValue">，推荐图片比例：{{prcScaleValue}}</span>
    </div>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="图标预览">
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'

export default {
  name: 'MultiImageUpload',
  props: {
    // 图片属性数组
    value: Array,
    // 模块名称
    module: String,
    // 图片比例说明
    prcScale: String,
    // 控件样式名
    uploadClassName: String,
    //最大上传图片数量
    maxCount: {
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      moduleData: {
        name: this.$props.module,
      },
      headers: {
        Authorization: getToken(),
      },
      dialogVisible: false,
      dialogImageUrl: null,
      prcScaleValue: this.$props.prcScale,
      localUploadUrl: process.env.VUE_APP_BASE_API + "/local/file/upload", // 上传的图片服务器地址
      uploadNum: 0,
      oldImgLength: 0,
      uploadFileClass: this.$props.uploadClassName,
    };
  },
  computed: {
    fileList() {
      let fileList = [];
      for (let i = 0; i < this.value.length; i++) {
        let imageName = this.value[i].substr(this.value[i].lastIndexOf("/") + 1);
        fileList.push({
          name: imageName,
          url: process.env.VUE_APP_FILE_URL + this.value[i],
        });
      }
      return fileList;
    }
  },
  methods: {
    emitInput(fileList) {
      let inputValue = [];
      for (let i = 0; i < fileList.length; i++) {
        inputValue.push(fileList[i].url);
      }
      this.$emit('input', inputValue);
    },
    handleRemove(file, fileList) {
      let otherFileList = [];
      for (let i = 0; i < this.value.length; i++) {
        if (!file.url.endsWith(this.value[i])) {
          otherFileList.push({
            url: this.value[i]
          });
        }
      }
      this.emitInput(otherFileList);
    },
    handlePreview(file) {
      this.dialogVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      this.oldImgLength = this.value.length;
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG | PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handFileChange(files, fileList) {
      var upload_img = document.getElementsByClassName(this.$props.uploadClassName)
      if (upload_img && upload_img.length > 0) {
        var upload = upload_img[0].getElementsByTagName('input');
        if (upload && upload.length > 0 && upload[0].files && upload[0].files.length > 0) {
          this.uploadNum = upload[0].files.length;
        }
      }
    },
    handleUploadSuccess(res, file) {
      let url = res.type + "/" + res.realName;
      this.value.push(url);
      let resultFileList = [];
      for (let i = 0; i < this.value.length; i++) {
        resultFileList.push({
          url: this.value[i]
        });
      }
      console.log("上传图片数量", this.uploadNum);
      console.log("上传图片差值", this.value.length - this.oldImgLength);
      if ((this.value.length - this.oldImgLength) == this.uploadNum) {
        console.log("设置图片");
        this.emitInput(resultFileList);
      }
    },
    handleExceed(files, fileList) {
      this.$message({
        message: '最多只能上传' + this.maxCount + '张图片',
        type: 'warning',
        duration: 1000
      });
    },
  }
}
</script>
